package unq.tpi.persistencia.performanceEj.daos;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.hibernate.classic.Session;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;

import unq.tpi.persistencia.performanceEj.model.Department;
import unq.tpi.persistencia.util.SessionManager;

public class DepartmentDAO {

	public Department getByName(final String name) {
		Session session = SessionManager.getSession();
		return (Department) session.createCriteria(Department.class)
				.add(Restrictions.eq("name",name))
				.uniqueResult();
	}

	public Department getByCode(String num) {
		Session session = SessionManager.getSession();
		return (Department) session.createQuery("select d from Department d join fetch d.employees e  join fetch e.titles t join fetch e.salaries s where d.number = :num and s.to = '9999-01-01' ")
					.setString("num", num).uniqueResult();
	}

	@SuppressWarnings("unchecked")
	public List<Department> getAll() {
		Session session = SessionManager.getSession();
		return session.createCriteria(Department.class).list();
	}

	public double getTotalSalarys(String num){
		Session session = SessionManager.getSession();
		SimpleDateFormat textFormat = new SimpleDateFormat("yyyy-MM-dd");
		String paramDateAsString = "9999-01-01";
		Date myDate = null;

		try {
			myDate = textFormat.parse(paramDateAsString);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return (Double) session.createCriteria(Department.class)
				.add(Restrictions.eq("number", num))
				.createAlias("employees", "emp")
				.createAlias("emp.salaries", "salarie")
				
				.add(Restrictions.eq("salarie.to", myDate))
				.setProjection(Projections.sum("salarie.amount"))
				.uniqueResult();
				
		
	}
	
}
